package com.xuanwei.core.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuanwei.core.courier.ZTQuery;
import com.xuanwei.core.entity.CourierInfo;
import com.xuanwei.core.enums.CourierStatus;
import com.xuanwei.core.exception.XwException;
import com.xuanwei.core.service.IXwOrderCourierService;
import com.xuanwei.dao.entity.XwOrderCourier;
import com.xuanwei.dao.mapper.XwOrderCourierMapper;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mjy
 * @since 2019-07-17
 */
@Service
public class XwOrderCourierServiceImpl extends ServiceImpl<XwOrderCourierMapper, XwOrderCourier> implements IXwOrderCourierService {


    @Override
    public CourierInfo queryCourier(Integer orderId) {

        XwOrderCourier courier = getOne(new QueryWrapper<XwOrderCourier>()
                .eq("order_id", orderId));

        if (courier == null) {
            throw new XwException("该订单物流不存在");
        }
        LocalDateTime updateTime = courier.getUpdateTime();
        LocalDateTime now = LocalDateTime.now();
        long seconds = Duration.between(updateTime, now).getSeconds();
        String jsonInfo = courier.getJsonInfo();
        List<CourierInfo.Info> infos = JSONObject.parseArray(jsonInfo, CourierInfo.Info.class);
        CourierInfo courierInfo = new CourierInfo();
        //已签收的快递和快递信息更新在两小时内的,只需要查询自己
        if (courier.getStatus().equals(CourierStatus.SUCCESS.getCode()) || seconds < 2 * 3600) {
            courierInfo.setInfos(infos);
            courierInfo.setStatus(courier.getStatus());
        } else {
            //todo 暂时只支持中通
            ZTQuery ztQuery = new ZTQuery();
            String courierNo = courier.getCourierNo();
            try {
                courierInfo = ztQuery.query(courierNo);
                courier.setStatus(courierInfo.getStatus());
                courier.setJsonInfo(JSON.toJSONString(courierInfo.getInfos()));
                courier.setUpdateTime(LocalDateTime.now());
                //修改到数据库
                updateById(courier);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return courierInfo;
    }


}
